
var personnelmanagement = angular.module("personnelmanagement", ['angularFileUpload','vModal', 'tm.pagination', 'ngAnimate', 'loadModule','PensonSelector', 'dropdownApp', 'btnconqitk','nstdirective','nspermirective'])
 .factory('addUserFactory', function (vModal) {
     return vModal({
         controller: 'addUserModal',
        controllerAs: 'addUserFactory',
         templateUrl: '/system/views/personnel/newlyadded.html'
     });
 })

//人员首页
.controller('personnelmanagementcontroller', ['$scope', '$rootScope', '$stateParams','$rootScope', function ($scope, $rootScope, $stateParams,$rootScope) {
$scope.btnlist = { savefun: false, addinfo: false, editinfo: false, delinfo: false };
    if($stateParams.id==""){
        $rootScope.currentTab =0;
    }else{
        $rootScope.currentTab = $stateParams.id;    //默认页面地址rootscopepathplay 路由名称     
    }

    if($stateParams.routename==""){
        $rootScope.btnTab = "index.personnelmanagement";
    }else{
        $rootScope.btnTab =$stateParams.routename;
    }

    $scope.childobj = function(){        
        var obj;
        angular.forEach($rootScope.rootscopeauthority, function(data,index,array){
            if(data.id =='5b820605e133c5dd106335caec6fdfac')
            {
                obj = data;                          
            }
        });                
        return obj;
    }
//    //监听路由跳转
//    $rootScope.$on('$stateChangeStart', function (evt, toState, toParams, fromState, fromParams) {
//        //console.log({evt,toState,toParams,fromState,fromParams});        
//        $scope.btnTab = toState.name;    //获取当前地址的路由名称
//    });

    $scope.personnelauthority = $scope.childobj().childroute;   // 人员路由控制    
    //选中方法
//    $scope.onClickTabS = function (url) {
//        $scope.currentTab = url;        
//        //$scope.currentTab = $stateParams.id;        
//    }
    //修改选中样式
    $scope.isActiveTab = function (tabUrl) {
        if($scope.currentTab == "HOME" && tabUrl == 0)
        {
            return true;
        }else{
            return tabUrl == $scope.currentTab;
        }
    }
} ])
/*
// 添加人员
.controller('addUserModal', ['$scope', 'addUserFactory', 'Restangular', function ($scope, addUserFactory, Restangular) {
  
    $scope.userstatestr = [{ stateval: "1", statestr: "正常" }, { stateval: "0", statestr: "冻结"}];
    $scope.userslivestr = ["学员", "教师", "管理员"];

    console.log($scope.title + "_1");

    //编辑
    if ($scope.title != "") {
        //        Restangular.one("/personnelManagement").customPOST({ name: "My Message" }, "personnelGetKey", { user_ID: $scope.title }).then(function (data) {
        //            console.log(data.errorcode);
        //            $scope.loaddata();
        //        }, function errorCallback() {
        //            console.log("连接服务器失败！");
        $scope.user_no = "";
        $scope.user_account = "";
        $scope.user_pwd = "";
        $scope.userstat = "";
        $scope.userpowerLV = "";
        $scope.user_name = "";
        $scope.user_email = "";
        $scope.user_phone = "";
        $scope.user_orglist = [{ "organization_ID": "1111", "organization_Name": "组织名称1", "isBoss": "0" }, { "organization_ID": "2222", "organization_Name": "组织名称2", "isBoss": "1" }, { "organization_ID": "3333", "organization_Name": "组织名称3", "isBoss": "0"}]; //"  [{ \"organization_ID\": \"1111\",\"organization_Name\": \"组织机构名称1\", \"isBoss\": \"0\" }, { \"organization_ID\": \"2222\", \"organization_Name\": \"组织机构名称2\", \"isBoss\": \"1\" }, { \"organization_ID\": \"3333\", \"organization_Name\": \"组织机构名称3\", \"isBoss\": \"0\"}] ";
        //        });
    }
    //关闭用户编辑、新增页面
    $scope.closeuser = function () { addUserFactory.deactivate(); }
      var addu = this;
    addu.closeuser = addUserFactory.deactivate;    

    //打开功能权限窗口
    $scope.addgongnengchuangkou = function () {
        $scope.abc = false;
    };
    //保存用户信息
    $scope.saveuser = function () {
        //基本信息
        console.log("userObj={ \"user_ID\": \"123123\", \"user_No\": \"" + $scope.user_no + "\", \"user_Account\": \"" + $scope.user_account + "\", \"user_Pwd\": \"" + $scope.user_pwd + "\", \"state\": \"" + $scope.userstat + "\", \"powerLV\": \"" + $scope.userpowerLV + "\", \"user_Name\": \"" + $scope.user_name + "\", \"email\": \"" + $scope.user_email + "\", \"phone\": \"" + $scope.user_phone + "\" }");
    }
} ])
*/
// 人员列表页面
.controller('personnelIMcontroller', ['$scope', '$rootScope', 'addUserFactory','$timeout','$location','$http','$stateParams','FileUploader','MsgCon', 'Msg', 'RequestPopService','sysUserInfo', '$state',function 
($scope, $rootScope, addUserFactory,  $timeout,$location,$http,$stateParams,FileUploader,MsgCon,Msg,RS,sysUserInfo,$state) {   

    $scope.btnlist={addinfo:false,editinfo:false,delinfo:false};
    $scope.personToken = sysUserInfo.getuserinfotoken();
  $scope.lvid=sysUserInfo.getuserinfo().powerLV;
     $scope.sendFlag  = false;// 自动通知变量
     $scope.userurl = $rootScope.userurl;
    //********自动通知点击事件
    $scope.AutoNotification = function(){
         $scope.sendFlag = !$scope.sendFlag;
         lorem.sendFlag = $scope.sendFlag;
    }
    $scope.addcomplexnum = function(num){
            return parseInt(num) > 9 ? num : "0"+ num;
    }
    // **************************************************文件上传开始***************************************************
    $scope.exUserList = [];
    var uploader = $scope.uploader = new FileUploader();
         // 回调    (目前一次上传一个)
    uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {     // 选择文件后失败       0
        console.info('onWhenAddingFileFailed', item, filter, options);        
    };    
    uploader.onAfterAddingFile = function (fileItem) {  // 选择文件后 （成功）   0          
        console.info('onAfterAddingFile', fileItem);
         if (uploader.isUploading) {
            Msg.info("有文件正在上传。。");
            return;
        }
        //fileItem.url ="http://localhost:8080/PersonnelSelector/ExcelImport?user_ID="+sysUserInfo.getuserinfo().user_ID+"&user_Name="+sysUserInfo.getuserinfo().user_Name+"&import_Type=1&organization_ID="+sysUserInfo.getuserinfo().organization_ID+"&send_flag="+$scope.sendFlag+"&powerLV="+sysUserInfo.getuserinfo().powerLV+"&organization_Name="+sysUserInfo.getuserinfo().organization_Name; // 上传地址http://login.study.brandwisdom.cn
        fileItem.url =$rootScope.userurl+"/PersonnelSelector/ExcelImport?user_ID="+sysUserInfo.getuserinfo().user_ID+"&user_Name="+sysUserInfo.getuserinfo().user_Name+"&import_Type=1&organization_ID="+sysUserInfo.getuserinfo().organization_ID+"&send_flag="+$scope.sendFlag+"&powerLV="+sysUserInfo.getuserinfo().powerLV+"&organization_Name="+sysUserInfo.getuserinfo().organization_Name+"&organizationName="+sysUserInfo.getuserinfo().orgfristname+"&organizationId="+sysUserInfo.getuserinfo().orgfrist+"&userGroupName="+sysUserInfo.getuserinfo().groupfristname+"&userRoleName="+sysUserInfo.getuserinfo().rolefristname; // 上传地址
        var d = new Date();
        var da = d.getFullYear()+"-"+$scope.addcomplexnum(d.getMonth()+1)+"-"+$scope.addcomplexnum(d.getDate())+" "+$scope.addcomplexnum(d.getHours())+":"+$scope.addcomplexnum(d.getMinutes())+":"+$scope.addcomplexnum(d.getSeconds());                
        var name =fileItem.file.name;
        // 创建一个文件上传的对象 name.substring(0,name.lastIndexOf("."))
        $scope.obj  = {
            "log_Name": da.replace(/-(.*?)/g,'').replace(/:(.*?)/g,'').replace(' ',''), // 文件名字不带扩展
            "import_Type": "1",
            "import_Time":da,
            "import_State": "上传中",
            "user_Name": sysUserInfo.getuserinfo().user_Name,
            "log_Path":"",
            "import_Num":"0"
        };
        $scope.exUserList.unshift($scope.obj);
        uploader.uploadAll();
    };
    uploader.onAfterAddingAll = function (addedFileItems) { // 选择文件后添加到队列   1 
        console.info('onAfterAddingAll', addedFileItems);
        //uploader.uploadAll();
    };
    // 开始上传
    uploader.onBeforeUploadItem = function (item) {    // 2 上传之前一项
        console.info('onBeforeUploadItem', item);
    };
    uploader.onProgressItem = function (fileItem, progress) {   // 3 上传进度
        console.info('onProgressItem', fileItem, progress);
        $scope.exUserList[0].import_Num = progress;    // 上传进度
        if(progress == 100){    // 上传完成后改成处理中
            $scope.exUserList[0].import_State = "处理中";
        }       
    };
    uploader.onProgressAll = function (progress) {      //4 队列进度
        console.info('onProgressAll', progress);
    };
    uploader.onSuccessItem = function (fileItem, response, status, headers) {   // 5上传成功
        console.info('onSuccessItem', fileItem, response, status, headers); //fileItem 请求信息 response: 返回值status: 返回状态  headers: 请求头          
        if(response.errorcode == "0"){
            $scope.exUserList[0].log_Path = response.data.log_Path;
            $scope.exUserList[0].import_Num = response.data.import_Num;
            $scope.exUserList[0].import_State =response.data.import_State;  
            $scope.exUserList[0].log_Name =  response.data.log_Name;   
            if($scope.exUserList[0].import_State == "失败"){
				Msg.warning("请下载日志文件查看信息");            		
            }

        } else if(response.errorcode == "1"){// 上传地址有问题
            $scope.exUserList[0].import_State ="失败";
        }else if(response.errorcode == "24"){// 上传地址有问题
            $scope.exUserList[0].import_State ="用户编号或用户账号为空";
        }
    };
    uploader.onErrorItem = function (fileItem, response, status, headers) {     // 5上传失败
        console.info('onErrorItem', fileItem, response, status, headers);
        $scope.exUserList[0].import_State ="失败";
        Msg.error("连接不上服务器");
        uploader.clearQueue();
    };
    uploader.onCancelItem = function (fileItem, response, status, headers) {    //5取消上传
        $scope.exUserList[0].import_State ="取消";
        console.info('onCancelItem', fileItem, response, status, headers);
    };
    uploader.onCompleteItem = function (fileItem, response, status, headers) {  //6     单文件上传完成
        console.info('onCompleteItem', fileItem, response, status, headers);
    };
    uploader.onCompleteAll = function () {  // 6 单文件上传完成或者队列上传完成的时候
        console.info('onCompleteAll');     
        uploader.clearQueue();  // 上传完毕清除队列
    };
    // 过滤（未知）
    uploader.filters.push({
        name: 'customFilter',
        fn: function (item /*{File|FileLikeObject}*/, options) {
            return this.queue.length < 10;
        }
    });

        // 获取文件上传的信息
        //    $http({
        //                url: '/api/test/exceluserlist.json',
        //                method: 'GET'
        //           }).success(function(data, header, config, status) {           
        //                if(data.errorcode == "0"){
        //                    $scope.exUserList = data.datas;                      
        //                }                
        //           }); 
        var d = new Date();
        var time = d.getFullYear()+"-"+$scope.addcomplexnum(d.getMonth()+1)+"-"+$scope.addcomplexnum(d.getDate());
        var timeold = d.getFullYear()+"-"+$scope.addcomplexnum(d.getMonth()+1)+"-"+$scope.addcomplexnum(d.getDate()-1);// 昨天
        $scope.todayFlag = true;
        //   获取数据 0 今天 1昨天        
        $scope.getToday = function(num){
            var timenew = time
            if(num == 1){
                timenew = timeold;
                 $scope.todayFlag = false;
            }else{
                $scope.todayFlag = true;
            }
            RS.GetImportList({organization_ID:sysUserInfo.getuserinfo().organization_ID, user_ID:sysUserInfo.getuserinfo().user_ID, powerLV:sysUserInfo.getuserinfo().powerLV, time: timenew }).then(function(data){                            
                    if(data.errorcode == 0){// 成功
                        if(data.datasJson != "[null]"&&data.datasJson!=undefined&&data.datasJson.length>0)
                        {
                            $scope.exUserList = JSON.parse(data.datasJson);                    
                            $scope.exUserList.forEach(function(data,index){
                                data.import_Time=$scope.getDate(data.import_Time);
                            });
                        }else{
                            $scope.exUserList=[];
                        }
                  }                               
                }, function callback() {                                
            });                 
         }

         $scope.getDate=function(time) {
            var date = new Date(time);
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                    + " " + date.getHours() + seperator2 + date.getMinutes()
                    + seperator2 + date.getSeconds();
            return currentdate;
        }

         $scope.getToday(0); //加载时候先加载今天的
    $scope.getclass = function(flag){
        if(flag == "失败"){
            return "personneladdrysb";
        }        
    }    
    $scope.shownum = function(sta,num){
    try{
             if(num.indexOf('/')>0){   
                return sta + " ("+num+")" ;
             }else{
                return sta;
             }
         }catch(e){ return sta;}
    }
    $scope.progressStryle = function(num){      
        try{
            if(num.indexOf('/')>0){            
                num  = (num.split('/')[0]/num.split('/')[1])  *100; 
            }  
        }catch(e){}
        if(num || num == 0){//  有值的时候
            return {"width": num+"%"};
        }else{
            return {"width":"100%"};
        }
    }
    // **************************************************文件上传结束***************************************************    
    var lorem = { title: '',sendFlag: false,objinfo:null };
     //*********HOME 调用过来的**********
     if($stateParams.id =="HOME"){
        lorem.title=""; addUserFactory.activate(lorem);
        $stateParams.id="";
     }     
    /** 人员列表复选框 ** 开始 **/
    $scope.user = { userinfo: [] };
    //checkbox全选
    $scope.checkAll = function () {
        var a = document.getElementById("checkall")
        if($scope.user.userinfo.length == $scope.names.length){
            $scope.uncheckAll();
            a.checked = false;
        }else{
            $scope.user.userinfo = angular.copy( $scope.names); 
            a.checked = true;
        }
    };
    //checkbox取消全选
    $scope.uncheckAll = function () { 
        $scope.user.userinfo = []; 
    };

    $scope.checkFirst = function () {
        $scope.user.userinfo.splice(0, $scope.user.userinfo.length);
        $scope.user.userinfo.push('guest');
    };
    /** 人员列表复选框 ** 结束 **/


    $scope.menudate = $rootScope.rootscopeauthority;
    $scope.addflag = false; //新增的显示隐藏  
    
    //添加人员 panel
    $scope.addinfo = function () {
        $scope.addflag = true;
        $scope.personneladdstyle ={ "height":document.documentElement.clientHeight - 90 + "px"};
        //$scope.adduser();
    }

   //***************************************筛选开始*********************************************
        //复合筛选按扭      
       $scope.checkedflag = true;
       $scope.checkedclick = function(){    
            $scope.checkedflag = !$scope.checkedflag;
            if($scope.checkedflag){
                $scope.GetUserList("",0); 
            }else{
//                $scope.playGetList();
                $scope.GetUserList("",110);  // 重置
            }
            //$scope.GetUserList("",0); 
        }    
        //左侧选择器初始化
        $scope.ApiData={
	        windowModal:"3",//调用模式 1弹窗模式 2宽度大于450 3 宽度小于450
	        ViceOrgOpen:false,//HtmlOrg弹框样式 关闭 选择器再次引用选择器样式
	        ViceGroupOpen:false,//HtmlOrg弹框样式 关闭 选择器再次引用选择器样式
	        ViceRoleOpen:false,//HtmlOrg弹框样式 关闭 选择器再次引用选择器样式
            ApiOpen:true,//为true时 页面打开选择器 false 关闭控制器
                 menu:[//进入人员选择器的菜单         
                     { "id":"Org"},
                     {"id":"Group"},
                    {"id":"Role"}
                 ],
                "ViceuserRoleList": [//传入的角色列表 再次点击 查询 双向绑定不能影响数据源

                ],
                "ViceuserOrgList": [//传入的部门列表 再次点击 查询 双向绑定不能影响数据源
                
                ],
                "ViceuserGroupList": [//传入的用户组 再次点击 查询 双向绑定不能影响数据源

                ],
            userOrgList:[],
            userRoleList:[],
            userGroupList:[],
            hasNullOrg:true,//显示空部门
            selectsNullOrg:false//选中空部门
        };
         //声明唯一部门对象
        $scope.OrgObj={
            organization_ID:"",
            organization_Name:"",
            parentId:"",
            parentName:"",
            organization_Num:0,
            organization_Sort:"",
            organization_No:"",
            orgOutsidePhone:"",
            orgHousePhone:"",
            Phone:""
        };     
          //声明唯一角色对象
        $scope.RolesObj={
            roles_ID:"",
            roles_Name:"",
            parentId:"",
            parentName:"",
            roles_Num:0,
            roles_Sort:"",
            roles_No:"",            
        };     
         //声明唯一角色对象
        $scope.GroupObj={
            userGroup_ID:"",
            userGroup_Name:"",
            parentId:"",
            parentName:"",
            userGroup_Num:0,
            userGroup_Sort:"",
            userGroup_No:"",            
        };     
             
        //由于人员选择器设计多选 在此处调用需要进行数据独立
        $scope.OnlyOne=function(PublicList){
            if (PublicList.length>1) {
              PublicList.splice(0, 1);
          }
        }
         //页面监听部门左侧列表选项
        var watch = $scope.$watch('ApiData.userOrgList',function(newValue,oldValue, scope){
            if(newValue==oldValue){
                return;
            }
            $scope.OnlyOne($scope.ApiData.userOrgList);//排除集合对象 
            $scope.OrgObj=$scope.GetSelectModal($scope.ApiData.userOrgList,$scope.OrgObj);//取单一             
            $scope.GetUserList($scope.OrgObj,5);         
           
        },true);
        //--- 监听角色
        var watch = $scope.$watch('ApiData.userRoleList',function(newValue,oldValue, scope){
            if(newValue==oldValue){
                return;
            }
            $scope.OnlyOne($scope.ApiData.userRoleList);//排除集合对象 
            $scope.RolesObj=$scope.GetSelectModal($scope.ApiData.userRoleList,$scope.RolesObj);//取单一                   
            $scope.GetUserList($scope.RolesObj,6);    
        },true);
        //--- 监听用户组
        var watch = $scope.$watch('ApiData.userGroupList',function(newValue,oldValue, scope){
            if(newValue==oldValue){
                return;
            }
            $scope.OnlyOne($scope.ApiData.userGroupList);//排除集合对象 
            $scope.GroupObj=$scope.GetSelectModal($scope.ApiData.userGroupList,$scope.GroupObj);//取单一                   
            $scope.GetUserList($scope.GroupObj,7);
        },true);
        var searchTypeList=[1];
        $scope.playparams={
                searchType:"",
                searchText:"",
                startTime:"",
                endTime:"",
                startDate:"",
                endDate:"",
                pageIndex:1,
                pageSize:0,      
                stype:1, 
                organization_ID:sysUserInfo.getuserinfo().organization_ID,
                userId:sysUserInfo.getuserinfo().user_ID,
                powerLV:sysUserInfo.getuserinfo().powerLV
         };
         $scope.url=$rootScope.userurl+"/PersonnelManagement/PersonnelGetList?searchType="+$scope.playparams.searchType+"&searchText="+$scope.playparams.searchText+"&startTime="+$scope.playparams.startTime+"&endTime="+$scope.playparams.endTime+"&startDate="+$scope.playparams.startDate+"&endDate="+$scope.playparams.endDate+"&orderbyfield="+$scope.playparams.orderbyfield+"&organization_ID="+$scope.playparams.organization_ID+"&type=2&userId="+$scope.playparams.userId+"&powerLV="+$scope.playparams.powerLV;
         
         $scope.GetTime=function(){
            $scope.playparams.startTime=document.getElementById("startTime").value;
            $scope.playparams.endTime=document.getElementById("endTime").value;
        }

    $scope.GetDate=function(){
            $scope.playparams.startDate=document.getElementById("startDate").value;
            $scope.playparams.endDate=document.getElementById("endDate").value;
        }
        //处理下拉框选择的内容 
        $scope.placeholder = "请输入姓名支持模糊查询";
         $scope.optionCheck=function(TypeIndex){
         $scope.playparams.searchText = "";
            TypeIndex =  parseInt(TypeIndex);
             switch(TypeIndex){
                case 1:
                    $scope.placeholder = "请输入姓名支持模糊查询";
                break;
                case 2:
                    $scope.placeholder = "请输入邮箱支持模糊查询";
                break;
                case 3:
                    $scope.placeholder = "请输入电话号码支持模糊查询";
                break;
                case 10:
                    $scope.placeholder = "请输入登录账号支持模糊查询";
                break;
            }
            //类型1 2 3 4 8 9 不可共存
            if (TypeIndex==1||TypeIndex==2||TypeIndex==3||TypeIndex == 4||TypeIndex==8||TypeIndex==9  || TypeIndex == 10) {
              for(var i = 1, length1 = 4; i <= length1; i++){
                var isHas=$scope.containsObj(searchTypeList,i);
                if (isHas>-1) {
                  searchTypeList.splice(isHas,1);
                }
              }
              var isHas=$scope.containsObj(searchTypeList,8);
                if (isHas>-1) {
                  searchTypeList.splice(isHas,1);
                }
              isHas=$scope.containsObj(searchTypeList,9);
                if (isHas>-1) {
                    searchTypeList.splice(isHas,1);
               }
               isHas=$scope.containsObj(searchTypeList,10);
                if (isHas>-1) {
                    searchTypeList.splice(isHas,1);
               }
            }
            searchTypeList.push(TypeIndex);            
        }
        //判断数组中是否包含此元素
        $scope.containsObj = function(arr, obj) {  
          try {
           var i = arr.length;  
            while (i--) {  
                if (arr[i] === obj) {  
                  return i;  
                }  
             }  
              return -1; 
            } catch(e) {
                // statements
                return -1;
              }
            }
      // 回车查询
      $scope.myKeyup = function(e){
            var keycode = window.event?e.keyCode:e.which;                        
            if(keycode==13){                
                $scope.AddSelect();
            }

        }
    // 调用查询
        $scope.AddSelect = function(){         
            $scope.playparams.searchType =  searchTypeList.join(',');            
//            if($scope.checkedflag){
//                $scope.GetUserList("",0); 
//            }else{
//                $scope.playGetList();
//            }
                $scope.GetUserList("",0); 
        }

         //--获取用户列表 -- 监听页面上有变动则进进入
        // -- obj:组织机构 用户组 角色
        // -- searchT： 5:组织机构 6:用户组 7:角色                
        var searchTypeListNew = [];
        $scope.GetUserList=function(Obj,searchT){                    
            // [数组]1:姓名搜索或拼音简写模糊搜索,2:邮箱搜索,3:手机号搜索,4:按时间段搜索,5:按用户部门搜索,6:按角色搜索、7:按用户组搜索、8:按用户状态搜索、9:按系统角色搜索                          
//            if(searchT == 110){           
                searchTypeListNew = [];
//            }
            var listparams={ // 请求参数
                searchType:"",
                searchText:"",
                startTime:$scope.playparams.startTime,
                endTime:$scope.playparams.endTime,
//                startTime:"",
//                endTime:"",
                startDate:"",
                endDate:"",
                pageIndex:1,
                pageSize:10,
                organization_ID:sysUserInfo.getuserinfo().organization_ID,
                userId:sysUserInfo.getuserinfo().user_ID,
                powerLV:sysUserInfo.getuserinfo().powerLV
            };                 
            
            if($scope.checkedflag){      // 判断是不是复合筛选                
                //searchTypeList.push($scope.playparams.searchType);
                if($scope.OrgObj){      //5 
                    if(!listparams.hasOwnProperty("userOrgList")){
                        listparams.userOrgList = [];
                    }
                    if($scope.OrgObj.organization_ID!="" && $scope.OrgObj.organization_Name!=""){
                        searchTypeListNew.push(5);
                        listparams.userOrgList.push({organization_ID:$scope.OrgObj.organization_ID,organization_Name:$scope.OrgObj.organization_Name});
                    }
                }
                if($scope.RolesObj){    // 6
                    if(!listparams.hasOwnProperty("userRoleList")){
                        listparams.userRoleList = [];
                    }
                    if($scope.RolesObj.roles_ID!=""&& $scope.RolesObj.roles_Name!=""){
                        searchTypeListNew.push(6);
                        listparams.userRoleList.push({roles_ID:$scope.RolesObj.roles_ID,roles_Name:$scope.RolesObj.roles_Name});
                    }
                }
                if($scope.GroupObj){    //7
                    if(!listparams.hasOwnProperty("userGroupList")){
                        listparams.userGroupList = [];
                    }
                    if($scope.GroupObj.userGroup_ID!=""&& $scope.GroupObj.userGroup_Name!=""){
                        searchTypeListNew.push(7);
                        listparams.userGroupList.push({userGroup_ID:$scope.GroupObj.userGroup_ID,userGroup_Name:$scope.GroupObj.userGroup_Name});
                    }
                }
            }else{ // 非复合筛选              
                var isOutFlag = true;
                switch (searchT) {
                    case 5:
                      searchTypeListNew = [];
                      if($scope.OrgObj){      //5 
                        if(!listparams.hasOwnProperty("userOrgList")){
                            listparams.userOrgList = [];
                        }                        
                        searchTypeListNew.push(5);
                        listparams.userOrgList.push({organization_ID:$scope.OrgObj.organization_ID,organization_Name:$scope.OrgObj.organization_Name});                              
                        $scope.ApiData.userRoleList =[];                
                        $scope.ApiData.userGroupList =[];
                        $scope.RolesObj = null;                                 
                        $scope.GroupObj =null;
                        isOutFlag = false;
                    }
                    break;
                    case 6:
                      searchTypeListNew = [];
                      if($scope.RolesObj){      //6
                            if(!listparams.hasOwnProperty("userRoleList")){
                                listparams.userRoleList = [];
                            }                         
                            searchTypeListNew.push(6);
                            listparams.userRoleList.push({roles_ID:$scope.RolesObj.roles_ID,roles_Name:$scope.RolesObj.roles_Name});
                            $scope.ApiData.userOrgList = [];                                            
                            $scope.ApiData.userGroupList =[];                            
                            $scope.OrgObj    =null;         
                            $scope.GroupObj =null;
                            isOutFlag = false;
                        }
                    break;
                    case 7:
                        searchTypeListNew = [];
                        if($scope.GroupObj){      //7
                            if(!listparams.hasOwnProperty("userGroupList")){
                                listparams.userGroupList = [];
                            }                            
                            searchTypeListNew.push(7);
                            listparams.userGroupList.push({userGroup_ID:$scope.GroupObj.userGroup_ID,userGroup_Name:$scope.GroupObj.userGroup_Name});
                            $scope.ApiData.userOrgList = [];                
                            $scope.ApiData.userRoleList =[];     
                            $scope.RolesObj = null;
                            $scope.OrgObj    = null;                                     
                            isOutFlag = false;                      
                        }
                    break;
                   // case 0 :
                    default:
                      
                    break;
                }           
                if(isOutFlag){ // 控制上面的有没有走
                  if($scope.OrgObj){      //5 
                            if(!listparams.hasOwnProperty("userOrgList")){
                                listparams.userOrgList = [];
                            }
                            searchTypeListNew = [];
                             if($scope.OrgObj.organization_ID!=""&& $scope.OrgObj.organization_Name!=""){
                                searchTypeListNew.push(5);
                                listparams.userOrgList.push({organization_ID:$scope.OrgObj.organization_ID,organization_Name:$scope.OrgObj.organization_Name});
                            }
                        }else if($scope.RolesObj){      //6
                            if(!listparams.hasOwnProperty("userRoleList")){
                                listparams.userRoleList = [];
                            }
                            searchTypeListNew = [];
                             if($scope.RolesObj.roles_ID!=""&& $scope.RolesObj.roles_Name!=""){
                            searchTypeListNew.push(6);
                            listparams.userRoleList.push({roles_ID:$scope.RolesObj.roles_ID,roles_Name:$scope.RolesObj.roles_Name});
                            }
                        }else if($scope.GroupObj){      //7
                                if(!listparams.hasOwnProperty("userGroupList")){
                                    listparams.userGroupList = [];
                                }
                                searchTypeListNew = [];
                                 if($scope.GroupObj.userGroup_ID!=""&& $scope.GroupObj.userGroup_Name!=""){
                                    searchTypeListNew.push(7);
                                    listparams.userGroupList.push({userGroup_ID:$scope.GroupObj.userGroup_ID,userGroup_Name:$scope.GroupObj.userGroup_Name});
                                }
                        }else{
                                searchTypeListNew = [];
                        }   
               }                          
            }
            //if(searchTypeList.length >0)  
            
             if(searchT == 110){                                //取消复合初始化
                    listparams.searchType =  searchTypeList.join(',');
                    $scope.ApiData.userOrgList = [];                
                    $scope.ApiData.userRoleList =[];                
                    $scope.ApiData.userGroupList =[];
             }else{
                listparams.searchType =  searchTypeList.join(',') +','+ searchTypeListNew.join(',');
                listparams.searchText =$scope.playparams.searchText;             
             }
            $scope.playparams = listparams;    
            if(!$scope.loadingflag) {// 控制不请求完不让请求

                $scope.url=$rootScope.userurl+"/PersonnelManagement/PersonnelGetList"
                +"?searchType="+$scope.playparams.searchType
                +"&searchText="+$scope.playparams.searchText
                +"&startTime="+$scope.playparams.startTime
                +"&endTime="+$scope.playparams.endTime
                +"&startDate="+$scope.playparams.startDate
                +"&endDate="+$scope.playparams.endDate
                +"&orderbyfield="+$scope.playparams.orderbyfield==undefined?'':$scope.playparams.orderbyfield
                +"&organization_ID="+$scope.playparams.organization_ID
                +"&type=2&userId="+$scope.playparams.userId
                +"&userRoleList="+JSON.stringify($scope.playparams.userRoleList)
                +"&userGroupList="+JSON.stringify($scope.playparams.userGroupList)
                +"&userOrgList="+JSON.stringify($scope.playparams.userOrgList)
                +"&powerLV="+$scope.playparams.powerLV;

                $scope.playGetList();            
           }
        }
        $scope.personList =[];
        $scope.loadingflag = false;
        $scope.playGetList= function(){
                $scope.loadingflag=true;
                 $scope.succ=false;
//            console.log($scope.playparams);  //$scope.promise加载名字
//            var hash = Object();
//            //hash['user_id'] = 'DALFJLDJSFLKDF';
//            hash['user_Name']='zhangsan';
//            $scope.promise=Restangular.one("personnelManagement").customPOST({name: "My Message"},"personnelGetListabc",{tableName:'Base_UserInfo',pkName:'user_ID',json:hash}).then(function(data)                             {  },function callback(){});
                $scope.promise=RS.personnelGetList($scope.playparams).then(function(data){                          
                    $scope.loadingflag = false;   
                    $scope.succ=true;
                    if(data.errorcode == 0){// 成功
                   // $scope.checkAll();
                        if(data.datas==undefined|| data.datas.length==0){
                            $scope.names =[];
    //            MsgCon.alert("暂无数据");
                        }else{
                            $scope.names = data.datas;
                        }
                        $scope.paginationConf.totalItems = data.numCount;
                        $scope.paginationConf.currentPage = data.pageIndex;   
                    
                        //$scope.promise = -1;                 
//                        console.log($scope.promise);
                    }                               
                }, function callback() {                     
                    $scope.loadingflag = false;           
                    //$scope.promise = -1;
                });            
            //负责人
            $scope.promiseperson=RS.personnelGetPersonList($scope.playparams).then(function(data){         
                $scope.loadingflag = false;    
                    try{
                        if(data.errorcode == 0){// 成功
                            if(data.datas==undefined||data.datas.length==0){
                                $scope.personList = [];
                            }else{
                                $scope.personList = data.datas ;
                            }
                        }else{
                            $scope.personList = [];
                        }
                        }catch(e){}               
                }, function callback() {                
                    $scope.loadingflag = false;
                    //$scope.promiseperson=0;
                });
               
        }
        //获取选择器所选对象
        $scope.GetSelectModal=function(PublicList,obj){
                try {
                       if (PublicList.length>0) {
                         return  obj= PublicList[0];
                     }
                } catch(e) {
                    console.log(e);
                }
        }
        $scope.excelUrlA="";
        $scope.loading = false;
        //请求人员导出
        $scope.downloadExcel=function(){
            var paramExcel=angular.copy($scope.playparams);
            paramExcel.type=2;
            $scope.loading = true;
            RS.personnelGetList(paramExcel).then(function(data){                          
                    $scope.loading = false;
                    if (data.errorcode == "0"&&data.errormsg!=undefined&&data.errormsg.length>0) {
                        window.location = data.errormsg;
                    }
                    else if (data.errorcode == "73"||(data.errorcode == "0"&&(data.errormsg==undefined||data.errormsg.length<=0))) {
                        setTimeout(function () {
                            $scope.downloadExcel();
                        }, 5000);
                        $scope.loading = true;
                        Msg.warning("正在统计请稍后..");
                    } else {
                        Msg.error("导出失败 ！");
                    }                             
                }, function callback() {                     
                    $scope.loadingflag = false;           
                });    
        }
        // *******************************筛选结束************************************* 
    //删除人员信息
    $scope.delinfo = function () {                   
        $scope.userid = [];
        if ($scope.user.userinfo.length > 0) {
            for (var i = 0; i < $scope.user.userinfo.length; i++) {
                $scope.userid.push($scope.user.userinfo[i].user_ID);
            }  
//            console.log( $scope.userid);                
            MsgCon.delnoicon().then(function(flag) {   // 删除弹框
                if(flag)
                {
                    RS.personnelDel({ userId: $scope.userid.join(","),userid:sysUserInfo.getuserinfo().user_ID }).then(function (data) {
                        if(data.errorcode==0){
                            $scope.user.userinfo = [];
                            $scope.playGetList();
                           var a = document.getElementById("checkall")
                            a.checked = false;
                        }else if(data.errorcode=="57"){
                             Msg.warning('选择的用户中包含超管或企业管理员，请重新选择！');
                        }
//                            console.log(data.errorcode);
                           
                    }, function errorCallback() {
                        console.log("连接服务器失败！");
                    });     
                }                        
            },function(p) {console.log('error') });                                                    
        }else{
            Msg.info('请选择一条记录！');
        }
    }

    $scope.addhide = function () {
        $scope.addflag = false;
    }
    //手动新增
    $scope.adduser = function () { lorem.title=""; addUserFactory.activate(lorem); };

    //用户编辑信息
    $scope.useredit = function (userid,userinfo) {
        if(!$scope.btnlist.editinfo){
            Msg.warning("无权限操作！");
            return;
        }
        lorem.objinfo=userinfo;
         lorem.title = userid;
         addUserFactory.activate(lorem);
        //console.log(userid);
    }

    //$scope.index1 = 1;
    $scope.succ=true;
    $scope.paginationConf = {
        currentPage:1,//$location.search().currentPage ? $location.search().currentPage :
        totalItems:0,
        itemsPerPage: 10,
        //pagesLength: 10,
        perPageOptions: [10, 20],
        //rememberPerPage: 'perPageItems',
        onChange: function () {
        if(!$scope.succ){
            Msg.info("正在查询中！");
            return;
        }else{
             if( (parseInt($scope.playparams.pageIndex) !=parseInt($scope.paginationConf.currentPage))||(parseInt($scope.playparams.pageSize) !=parseInt($scope.paginationConf.itemsPerPage))){
                    if($scope.paginationConf.currentPage==0){$scope.paginationConf.currentPage=1;}
                    $scope.playparams.pageIndex =$scope.paginationConf.currentPage;
                    $scope.playparams.pageSize = $scope.paginationConf.itemsPerPage;
                    $scope.playGetList();                
                }
        }
    }
    }

    $scope.loaddata = function () {
//        $scope.promise = Restangular.all('api/test').customGET("ngtabledata.json", { pageindex: $scope.paginationConf.currentPage }).then(function (retStr) {
//            $scope.names = retStr[0].userList;
//            $scope.paginationConf.totalItems = retStr[0].numCount;
//            $scope.paginationConf.currentPage = retStr[0].pageIndex;
//            //$scope.paginationConf.itemsPerPage=retStr[0].pageSize;                                
//            //totalItems 总共有多少条记录
//            //currentPage 当前所在的页（…默认第1页）
//            //itemsPerPage 每页展示的数据条数（…默认15条）
//            //pagesLength 分页条目的长度（如果设置建议设置为奇数）
//        });
    }

    //控制图标对应提示黑框的隐藏/显示
    $scope.showMsg = function (titletype) {
        if(titletype=="1"){
            $scope.showPerson=true;
        }else if(titletype=="2"){
            $scope.showComplex=true;
        }else if(titletype=="3"){
            $scope.autnotice=true;
        }
    }
    
    $scope.hideMsg = function (titletype) {
        if(titletype=="1"){
            $scope.showPerson=false;
        }else if(titletype=="2"){
            $scope.showComplex=false;
        }else if(titletype=="3"){
            $scope.autnotice=false;
        }
    }
 /*************************解除锁定*******************************/
 $scope.clearlock=function(){
    $scope.acid = [];
    $scope.userid = [];
        if ($scope.user.userinfo.length > 0) {
            for (var i = 0; i < $scope.user.userinfo.length; i++) {
                $scope.userid.push($scope.user.userinfo[i].user_ID);
                $scope.acid.push($scope.user.userinfo[i].user_Account);
            }  
//            console.log( $scope.userid);                
                    RS.clearlock({ userid: $scope.userid.join(","),useraccount:$scope.acid.join(",") }).then(function (data) {                    
                            if(parseInt(data)>=0){
                            Msg.success('帐号解除锁定');
                            console.log(data);
                            $scope.playGetList();
                        }
                    }, function errorCallback() {
                        console.log("连接服务器失败！");
                    });                                                                         
        }else{
            Msg.info('请选择一条记录！');
        }
 }     
 /***************************跳转api**********************************/
 $scope.goApi=function(){
 //$state.go("index.manager.api");
    window.open("http://www.jisupeixun.com/Home/helpinfo?key=31a970c4-b258");
 }

 $scope.optionCheck("10");

 //******************************修改人员所属企业**********************************/



} ]);
